/*------------------------------Summary-------------------------------------
 * Product Name : EMOP iOS Application Software
 * File Name	: REMCarViewController.m
 * Date Created : 张 锋 on 6/23/14.
 * Description  : IOS Application software based on Energy Management Open Platform
 * Copyright    : Schneider Electric (China) Co., Ltd.
--------------------------------------------------------------------------*/
#import "REMCarViewController.h"
#import <CoreMotion/CoreMotion.h>
#import "GCDAsyncSocket.h"
#import <MediaPlayer/MediaPlayer.h>


#define MSGLEN 19
#define MSG_DATA @"data|p:%4d;r:%4d;"
#define MSG_STAT @"stat|%14d"




@interface REMCarViewController ()

@property (nonatomic,strong) CMMotionManager *motionManager;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic) BOOL isStarted;

@property (nonatomic,strong) UIColor *startButtonOriginalColor;
@property (nonatomic,strong) MPMoviePlayerController *movieController;

@property (nonatomic) int lastPitch;
@property (nonatomic) int lastRoll;

@end

@implementation REMCarViewController

static GCDAsyncSocket *asyncSocket;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.isStarted = NO;
    
    self.buttonStart.layer.cornerRadius = 50;
    self.buttonBackward.layer.cornerRadius = 40;
    self.buttonForward.layer.cornerRadius = 40;
    
    [self.buttonConnect addTarget:self action:@selector(connectPressed) forControlEvents:UIControlEventTouchUpInside];
    
    [self startListenMotion];
}

-(void)startListenMotion
{
    self.motionManager = [[CMMotionManager alloc] init];
    
    [self.motionManager startDeviceMotionUpdatesToQueue:[[NSOperationQueue alloc] init] withHandler:^(CMDeviceMotion *motion, NSError *error) {
        dispatch_async(dispatch_get_main_queue(),^{
            double pitch = motion.attitude.pitch;
            double roll = motion.attitude.roll;
            
            double front = 0, back=0, left=0, right=0;
            if(pitch>0){
                front = 0;
                back = pitch;
            }
            else{
                front = ABS(pitch);
                back = 0;
            }
            
            if(roll>0){
                right = roll;
                left = 0;
            }
            else{
                right = 0;
                left = ABS(roll);
            }
            
            self.labelFront.text = [NSString stringWithFormat:@"%0.0f", front*1000];
            self.labelBack.text = [NSString stringWithFormat:@"%0.0f", back*1000];
            self.labelRight.text = [NSString stringWithFormat:@"%0.0f", right*1000];
            self.labelLeft.text = [NSString stringWithFormat:@"%0.0f", left*1000];
            
            int p = pitch * 1000;
            int r = roll * 1000;
            
            if(p>500) p=500;
            if(p<-500) p=-500;
            if(r>500) r=500;
            if(r<-500) r=-500;
            
            self.lastPitch = p;
            self.lastRoll = r;
        });
    }];
}

-(void)connectPressed
{
    if(asyncSocket==nil){
        asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        NSError *error = nil;
        
        if (![asyncSocket connectToHost:self.textIP.text onPort:[self.textPort.text intValue] error:&error]) {
            NSLog(@"Unable to connect to due to invalid configuration: %@", error);
        }
        else {
            NSLog(@"Connecting...");
        }
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(tick) userInfo:nil repeats:YES];
        
        [self.buttonConnect setTitle:@"Disconn" forState:UIControlStateNormal];
    }
    else{
        //[self send:@"byebye" withFormatLength:MSGLEN];
        NSLog(@"byebye!");
        [asyncSocket disconnect];
        asyncSocket = nil;
        
        [self.timer invalidate];
        self.timer = nil;
        
        [self.buttonConnect setTitle:@"Connect" forState:UIControlStateNormal];
    }
}

-(void)tick
{
    if(self.isStarted){
        [self sendPitch:self.lastPitch andRoll:self.lastRoll];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item
{
    [self.motionManager stopDeviceMotionUpdates];
    NSLog(@"Car exit.");
}


- (IBAction)startPressed:(id)sender {
    if([self.buttonStart.titleLabel.text isEqualToString:@"Start"]){
        self.isStarted = YES;
        //send command to call car's start method
        [self send:[NSString stringWithFormat:MSG_STAT, 1] withFormatLength:MSGLEN];
        
        //enable forward and backward buttons
        self.buttonForward.enabled = YES;
        self.buttonBackward.enabled = YES;
    
        //change text to stop
        [self.buttonStart setTitle:@"Stop" forState:UIControlStateNormal];
        self.startButtonOriginalColor = [self.buttonStart backgroundColor];
        self.buttonStart.backgroundColor = [UIColor redColor];
    }
    else{
        self.isStarted = NO;
        //send command to call car's stop method
        [self send:[NSString stringWithFormat:MSG_STAT, 0] withFormatLength:MSGLEN];
        
        //disable forward and backward buttons
        self.buttonForward.enabled = NO;
        self.buttonBackward.enabled = NO;
        
        //change text to start
        [self.buttonStart setTitle:@"Start" forState:UIControlStateNormal];
        self.buttonStart.backgroundColor = self.startButtonOriginalColor;
    }
}



- (IBAction)forwardPressed:(id)sender {
    [self sendPitch:500 andRoll:0];
}
- (IBAction)backwardPressed:(id)sender {
    [self sendPitch:-500 andRoll:0];
}

-(void)sendPitch:(int)pitch andRoll:(int)roll
{
    NSString *command = [NSString stringWithFormat:MSG_DATA, pitch,roll];
    
    NSLog(@"msg:%@",command);
    
    [self send:command withFormatLength:MSGLEN];
}

-(void)send:(NSString *)message withFormatLength:(int)length
{
    NSLog(@"sending message: %@", message);
    
    if(asyncSocket!=nil){
        while(message.length < length){
            message = [message stringByAppendingString:@"0"];
        }
        
        message = [message stringByAppendingString:@"\0"];
        NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
        [asyncSocket writeData:data withTimeout:-1.0 tag:0];
    }
    else{
        NSLog(@"socket is null");
    }
}

@end
